package com.luyang.framework.ddd.ability;

import com.alibaba.ttl.TransmittableThreadLocal;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.HashMap;
import java.util.Map;

/**
 * 能力上下文
 *
 * @author lu_yang
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class AbilityContext {

    private static final ThreadLocal<Map<String, Object>> CONTEXT = new TransmittableThreadLocal<>();

    /**
     * 初始化上下文
     *
     * @author lu_yang
     */
    protected static void initContext() {
        var con = CONTEXT.get();
        if (null == con) {
            CONTEXT.set(new HashMap<>(8));
            return;
        }

        CONTEXT.get().clear();
    }

    /**
     * 清理上下文
     *
     * @author lu_yang
     */
    protected static void clearContext() {
        CONTEXT.remove();
    }

    /**
     * 获取上下文内容
     *
     * @param key 键
     * @return T
     * @author lu_yang
     */
    @SuppressWarnings("unchecked")
    public static <T> T getValue(String key) {
        var con = CONTEXT.get();
        if (null == con) {
            return null;
        }
        return (T) con.get(key);
    }

    /**
     * 设置上下文参数
     *
     * @param key   键
     * @param value 值
     * @return void
     * @author lu_yang
     */
    public static void putValue(String key, Object value) {
        var con = CONTEXT.get();
        if (null == con) {
            CONTEXT.set(new HashMap<>(8));
            con = CONTEXT.get();
        }

        con.put(key, value);
    }
}
